import sys

from conf import settings
from core import main


class ManagementTool(object):
    """管理服务器."""
    center_args1, center_args2 = 50, '-'

    def __init__(self):
        self.script_argv = sys.argv
        self.commands = None

        # print(self.script_argv)

        self.verify_argv()

    def verify_argv(self):
        """
        核查参数时否合理.
            例:
            ['启动文件路径', 'start', 'ftp', 'server']
        """
        if len(self.script_argv) != 4:
            self.help_msg()

        action_type = self.script_argv[1]
        self.commands = self.script_argv[2:]
        if hasattr(self, action_type):
            func = getattr(self, action_type)
            func()
        else:
            self.help_msg()

    @staticmethod
    def help_msg():
        msg = """
             ------严格要求输入以下命令:------
                 ① start   ftp server
                 ② stop    ftp server
                 ③ restart ftp server
             """
        exit(msg)

    def start(self):
        """启动ftp服务."""
        if self.execute():
            print('FTP started successfully!')
            # FTPServer中可能用到ManagementTool中功能
            server = main.FTPServer(self, (settings.HOST, settings.PORT))
            server.serve_forever()
        else:
            self.help_msg()

    def execute(self):
        """解析命令."""
        args1, args2 = self.commands
        if args1 == 'ftp' and args2 == 'server':
            return True
        return False
